package org.kingtop.mybatis.mapper;

import org.apache.ibatis.session.Configuration;
import org.kingtop.mybatis.util.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * SqlInjector工厂类
 * 
 * @author 陈金波
 * @date 2018年1月9日 下午7:50:04
 * @Copyright: 2018 chen jinbo. All rights reserved.
 */
public class SqlInjectorFactory {

	private final Configuration configuration;

	/**
	 * 数据库类型
	 */
	private String dbType;

	public SqlInjectorFactory(Configuration configuration) {
		super();
		this.configuration = configuration;
	}

	/**
	 * 构建SQL注入类
	 * 
	 * @author 陈金波
	 * @date 2018年1月9日 下午7:49:47
	 * @param type
	 * @return
	 * @return SqlInjector
	 */
	public SqlInjector buildSqlInjector(Class<?> type) {
		if (this.dbType == null) {
			try {
				Connection connection = this.configuration.getEnvironment().getDataSource().getConnection();
				this.dbType = JdbcUtils.getDbType(connection.getMetaData().getURL());
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		SqlInjector sqlInjector = new SqlInjector(this.configuration, type, this.dbType);
		sqlInjector.init();
		return sqlInjector;
	}

}
